#pragma once

#include <vector>
#include <cassert>

namespace Log
{
#define DEFAULT_BUFFER_SIZE (1024 * 1024 * 10)
#define THRESHOLD_BUFFER_SIZE (1024 * 1024 * 80)
#define INCREMENT_BUFFER_SIZE (1024 * 1024 * 10)

    class Buffer
    {
    public:
        Buffer()
            : _buffer(DEFAULT_BUFFER_SIZE), _read_idx(0), _write_idx(0)
        {
        }

        // 向缓冲区写入数据
        void write(const char *data, size_t len)
        {
            // 空间不足则扩容
            resizeSufficiency(len);

            // 将数据拷贝到缓冲区
            std::copy(data, data + len, &_buffer[_write_idx]);
            // 将写指针向后偏移
            moveWriteIdx(len);
        }

        // 返回可读数据起始地址
        const char *begin()
        {
            return &_buffer[_read_idx];
        }

        // 返回可读数据长度
        size_t readAbleSize()
        {
            return (_write_idx - _read_idx);
        }

        // 返回可写数据缓冲区长度
        size_t writeAbleSize()
        {
            return (_buffer.size() - _write_idx);
        }

        // 对读指针进行向后偏移操作
        void moveReadIdx(size_t len)
        {
            assert(len <= readAbleSize());
            _read_idx += len;
        }

        // 重置读写位置，初始化缓冲区
        void reset()
        {
            _read_idx = 0;
            _write_idx = 0;
        }

        // 实现缓冲区交换操作
        void swap(Buffer &buffer)
        {
            _buffer.swap(buffer._buffer);
            std::swap(_read_idx, buffer._read_idx);
            std::swap(_write_idx, buffer._write_idx);
        }

        // 判断缓冲区是否为空
        bool empty()
        {
            return _read_idx == _write_idx;
        }

    private:
        // 对写指针进行向后偏移操作
        void moveWriteIdx(size_t len)
        {
            assert((_write_idx + len) <= _buffer.size());
            _write_idx += len;
        }

        // 调整缓冲区至充分大小
        void resizeSufficiency(size_t len)
        {
            if (len < writeAbleSize())
                return;
            size_t new_size = 0;
            if ((_buffer.size() + len) < THRESHOLD_BUFFER_SIZE)
            {
                new_size = _buffer.size() * 2;
            }
            else
            {
                new_size = _buffer.size() + INCREMENT_BUFFER_SIZE;
            }
            _buffer.resize(new_size);
        }

    private:
        std::vector<char> _buffer;
        size_t _read_idx;  // 当前可读数据的指针
        size_t _write_idx; // 当前可写数据的指针
    };
}